<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cates extends Model
{
    protected $table = "cates";
    protected $primaryKey = "cat_id";
    public $timestamps = false;
    protected $guarded = [];

   	/**
	 * 获取无限级分类
	 */
    public function getTree($cate, $parent_id = 0, $level = 0, $html = '--')
    {
        $tree = array();
        foreach ($cate as $v)
	 	{
            if ($v->parent_id == $parent_id) 
            {
                $v->level = $level + 1;
                $v->html = str_repeat($html, $level);
                $tree[] = $v;
                //print_r($tree);
                $tree = array_merge($tree, $this->getTree($cate, $v->cat_id, $level + 1, $html));
            }
        }
        return $tree;
    }
	
	/**
	 * 获取全部分类
	 */
	public function getAllCates()
	{
		return Cates::where('is_show',0)->get();
	}
	
	/**
	 * 获取栏目的所有子级
	 */
	public	function getChild($cid)
	{
        $tree = [];
        foreach ($this -> getAllCates() as $v)
	 	{
            if($v->parent_id == $cid) 
            {
                $tree[] = $v->cat_id;
                $tree = array_merge($tree, $this->getChild($v->cat_id));
            }
        }
        return $tree;
	}
	
	/**
	 * 拼接父级分类关键词
	 */
	public function getParentKeyword($cid)
	{
		if($cid != 0 )
		{
	        $kw = ' ';
	        foreach($this -> getAllCates() as $v)
		 	{
	            if($v->cat_id == $this::where('cat_id',$cid)->select('parent_id')->first()->parent_id) 
	            {
	                $kw .=  $v->cat_name;
	                $kw .=  $this->getParentKeyword($v->cat_id);
	            }
	        }
	        return $kw;			
		}

	}  
}
